package com.compdev.testutils.app;

import java.io.PrintStream;
import java.util.Scanner;

import com.compdev.testutils.counterstring.CounterStringManager;

public class CounterStringParser {

	public static final String ERROR_COUNTERSTRING_LENGTHS_MUST_BE_INTEGERS_MESSAGE = "Valid counterstring lengths are integers";
	public static final String EXIT_COMMAND_INPUT = "exit";
	public static final String INPUT_PROMPT_MESSAGE = "Input counterString length or [exit] to exit >";
	public static final String GENERATED_COUNTERSTRING_MESSAGE_OF_D_S = "Generated counterstring of %d%s";

	private String counterStringDelimiter;
	private int counterStringLength;
	private Scanner input;
	private PrintStream output;

	public CounterStringParser(Scanner input, PrintStream out,
			String counterStringDelimiter, int counterStringLength) {

		this.counterStringDelimiter = counterStringDelimiter;
		this.counterStringLength = counterStringLength;
		this.input = input;
		this.output = out;

	}

	public void process() {

		String counterStringLengthInput = "";

		CounterStringManager csm = new CounterStringManager(
				counterStringDelimiter);

		do {

			if (counterStringLength > 0) {
				csm.generateCounterStringToClipboard(counterStringLength);
				output.println(String.format(
						GENERATED_COUNTERSTRING_MESSAGE_OF_D_S,
						counterStringLength, counterStringDelimiter));
			}

			output.print(INPUT_PROMPT_MESSAGE);

			counterStringLengthInput = input.next();

			if (!counterStringLengthInput.trim().contentEquals(
					EXIT_COMMAND_INPUT)) {
				counterStringLength = getCounterStringLength(counterStringLengthInput);
			}

		} while (!counterStringLengthInput.trim().contentEquals(
				EXIT_COMMAND_INPUT));

	}

	private int getCounterStringLength(String counterStringLengthAsString) {
		int stringLength = 0;
		try {
			stringLength = new Integer(counterStringLengthAsString);
		} catch (Exception e) {
			output.println(ERROR_COUNTERSTRING_LENGTHS_MUST_BE_INTEGERS_MESSAGE);
		}
		return stringLength;
	}

}
